package com.sptpc.androidclass1029;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LongDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class TimerService extends Service {
    Thread mThread = new Thread(new MyThread());
    Handler handler = new Handler(Looper.myLooper());
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private class MyThread implements Runnable{
        @Override
        public void run() {
            while (true)
            {
                Log.d("Sptpc","Service is running");
                if(Thread.currentThread().isInterrupted()){
                    //处理中断逻辑
                    return;
                }
            }
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("Sptpc","开始线程");
        mThread.start();

//        handler = new Myhandle(Looper.myLooper());
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                handler.sendMessage(msg);
            }
        };
        Message msg = new Message();
        msg.obj = "testMessage";
        handler.sendMessage(msg);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mThread.interrupt();
        Log.d("Sptpc","销毁线程");
        Toast.makeText(this,"已终止该线程ID为：" + Thread.currentThread().getName(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("Sptpc","onStartCommad");
//        stopSelf();
        return super.onStartCommand(intent, flags, startId);
    }
    private class Myhandle extends Handler{
        public Myhandle(Looper looper)
        {
            super(looper);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Log.d("Sptpc","接受消息");

        }
    }
}
